<template>
    <div class="position-level-management">
        <pageTitle :title="'職務級別管理'" />

        <!-- 頂部搜索和按鈕區域 -->
        <div class="top-action-bar">
            <el-row :gutter="20" align="middle">
                <el-col :span="12">
                    <el-input placeholder="請輸入職級名稱或編號" v-model="searchQuery" class="search-input-with-button" clearable
                        @clear="handleSearch" @keyup.enter="handleSearch">
                        <template #append>
                            <el-button type="primary" @click="handleSearch">
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="12" class="action-buttons">
                    <el-button type="primary" @click="addPositionLevel">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>新增職級</span>
                    </el-button>
                    <el-button type="danger" @click="batchDelete" :disabled="selectedLevels.length === 0">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        <span>批量刪除</span>
                    </el-button>
                </el-col>
            </el-row>
        </div>

        <!-- 職級表格 -->
        <div class="position-level-table">
            <el-table :data="filteredLevels" style="width: 100%" v-loading="loading" class="no-border-table"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="code" label="職級編號" width="120" align="center" />
                <el-table-column prop="name" label="職級名稱" width="150" align="center" />
                <el-table-column prop="level" label="職級等級" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getLevelTagType(row.level)">
                            {{ getLevelText(row.level) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="職務描述" show-overflow-tooltip />
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editPositionLevel(row)">
                            編輯
                        </el-button>
                        <el-button type="danger" size="small" @click="deletePositionLevel(row)">
                            刪除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-wrapper">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :small="true" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 新增/編輯職級對話框 -->
        <el-dialog v-model="dialogVisible" :title="isEditMode ? '編輯職級' : '新增職級'" width="500px">
            <el-form :model="levelForm" :rules="levelRules" ref="levelFormRef" label-width="100px">
                <el-form-item label="職級編號" prop="code">
                    <el-input v-model="levelForm.code" placeholder="請輸入職級編號" />
                </el-form-item>
                <el-form-item label="職級名稱" prop="name">
                    <el-input v-model="levelForm.name" placeholder="請輸入職級名稱" />
                </el-form-item>
                <el-form-item label="職級等級" prop="level">
                    <el-select v-model="levelForm.level" placeholder="請選擇職級等級">
                        <el-option v-for="item in levelOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="職務描述">
                    <el-input v-model="levelForm.description" type="textarea" :rows="3" placeholder="請輸入職務描述" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitLevelForm">確定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import pageTitle from "@/components/pageTitle/pageTitle.vue"

// 響應式數據
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const selectedLevels = ref([])

// 職級列表數據
const positionLevels = ref([
    { id: 1, code: 'PL001', name: '初級職員', level: 1, description: '初級職位，負責基礎工作' },
    { id: 2, code: 'PL002', name: '中級職員', level: 2, description: '中級職位，有一定工作經驗' },
    { id: 3, code: 'PL003', name: '高級職員', level: 3, description: '高級職位，負責重要工作' },
    { id: 4, code: 'PL004', name: '主管', level: 4, description: '管理小型團隊' },
    { id: 5, code: 'PL005', name: '經理', level: 5, description: '管理部門或大型團隊' },
    { id: 6, code: 'PL006', name: '總監', level: 6, description: '負責整個業務線' },
    { id: 7, code: 'PL007', name: '副總裁', level: 7, description: '公司高層管理人員' },
    { id: 8, code: 'PL008', name: '總裁', level: 8, description: '公司最高管理層' }
])

// 職級等級選項
const levelOptions = ref([
    { value: 1, label: '1級 (初級)' },
    { value: 2, label: '2級 (中級)' },
    { value: 3, label: '3級 (高級)' },
    { value: 4, label: '4級 (主管)' },
    { value: 5, label: '5級 (經理)' },
    { value: 6, label: '6級 (總監)' },
    { value: 7, label: '7級 (副總裁)' },
    { value: 8, label: '8級 (總裁)' }
])

// 表單相關
const dialogVisible = ref(false)
const isEditMode = ref(false)
const levelForm = ref({
    id: null,
    code: '',
    name: '',
    level: null,
    description: ''
})
const levelRules = {
    code: [{ required: true, message: '請輸入職級編號', trigger: 'blur' }],
    name: [{ required: true, message: '請輸入職級名稱', trigger: 'blur' }],
    level: [{ required: true, message: '請選擇職級等級', trigger: 'change' }]
}
const levelFormRef = ref(null)

// 計算屬性
const filteredLevels = computed(() => {
    if (!searchQuery.value) {
        return positionLevels.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
    }
    return positionLevels.value.filter(level =>
        level.code.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        level.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
})

// 生命週期鉤子
onMounted(() => {
    fetchPositionLevels()
})

// 方法
const fetchPositionLevels = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        total.value = positionLevels.value.length
        loading.value = false
    }, 500)
}

const handleSearch = () => {
    currentPage.value = 1
    fetchPositionLevels()
}

const handleSelectionChange = (selection) => {
    selectedLevels.value = selection
}

const addPositionLevel = () => {
    isEditMode.value = false
    levelForm.value = {
        id: null,
        code: '',
        name: '',
        level: null,
        description: ''
    }
    dialogVisible.value = true
}

const editPositionLevel = (row) => {
    isEditMode.value = true
    levelForm.value = { ...row }
    dialogVisible.value = true
}

const deletePositionLevel = (row) => {
    ElMessageBox.confirm(`確定要刪除職級「${row.name}」嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        positionLevels.value = positionLevels.value.filter(item => item.id !== row.id)
        total.value = positionLevels.value.length
        ElMessage.success('刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const batchDelete = () => {
    if (selectedLevels.value.length === 0) {
        ElMessage.warning('請至少選擇一個職級')
        return
    }

    ElMessageBox.confirm(`確定要刪除選中的 ${selectedLevels.value.length} 個職級嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const selectedIds = selectedLevels.value.map(item => item.id)
        positionLevels.value = positionLevels.value.filter(item => !selectedIds.includes(item.id))
        selectedLevels.value = []
        total.value = positionLevels.value.length
        ElMessage.success(`已成功刪除 ${selectedIds.length} 個職級`)
    }).catch(() => {
        ElMessage.info('已取消批量刪除')
    })
}

const submitLevelForm = () => {
    levelFormRef.value.validate((valid) => {
        if (valid) {
            if (isEditMode.value) {
                // 更新職級
                const index = positionLevels.value.findIndex(item => item.id === levelForm.value.id)
                if (index !== -1) {
                    positionLevels.value[index] = { ...levelForm.value }
                }
                ElMessage.success('職級更新成功')
            } else {
                // 新增職級
                const newId = Math.max(...positionLevels.value.map(item => item.id), 0) + 1
                positionLevels.value.push({
                    ...levelForm.value,
                    id: newId
                })
                ElMessage.success('職級新增成功')
            }
            dialogVisible.value = false
            fetchPositionLevels()
        }
    })
}

const getLevelTagType = (level) => {
    const types = ['', 'success', 'info', 'warning', 'danger', 'primary', 'success', 'warning', 'danger']
    return types[level] || ''
}

const getLevelText = (level) => {
    const texts = ['', '初級', '中級', '高級', '主管', '經理', '總監', '副總裁', '總裁']
    return texts[level] || level
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchPositionLevels()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchPositionLevels()
}
</script>

<style scoped lang="less">
.position-level-management {
    padding: 20px;
    background-color: #fff;

    .top-action-bar {
        margin-bottom: 20px;
        padding: 16px 24px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        margin-top: 20px;

        .search-input-with-button {
            max-width: 500px;

            .el-input-group__append {
                background-color: var(--el-color-primary);
                color: white;
                border: none;

                &:hover {
                    opacity: 0.9;
                }
            }
        }

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }
    }

    .position-level-table {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;

        .no-border-table {

            :deep(.el-table__header),
            :deep(.el-table__body),
            :deep(.el-table__row),
            :deep(.el-table__cell) {
                border: none !important;
            }

            :deep(.el-table__header th) {
                background-color: #f4f8ff;
                font-weight: 600;
                padding: 20px;
            }

            :deep(.el-table__row):hover td {
                background-color: #f5f7fa !important;
            }
        }

        .pagination-wrapper {
            margin-top: 24px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>